package com.gk.chat.controller;

import com.gk.chat.common.R;
import com.gk.chat.pojo.Users;
import com.gk.chat.service.UsersService;
import com.gk.chat.utils.JwtUtil;
import com.gk.chat.utils.RSAUtil;
import com.gk.chat.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/v1/auth")
public class UsersController {

    @Value("${rsa.private-key}")
    private  String privateKey;

    @Autowired
    private UsersService usersService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 登录接口
     * @param loginUser
     * @return
     * @throws Exception
     */
    @PostMapping("/login")
    public ResponseEntity<R<Map<String, Object>>> login(@RequestBody Users loginUser) throws Exception {
//        log.info("mobile:{},password:{}", loginUser.getMobile(), loginUser.getPassword());
        //查询用户
        Users user=usersService.getUserByMobile(loginUser.getMobile());
        //判断用户是否存在
        if(user==null) {
            return ResponseEntity.badRequest().body(R.error("用户不存在"));
        }
        //判断密码是否正确
        if(!user.getPassword().equals(RSAUtil.decrypt(loginUser.getPassword(), privateKey))) {
            return ResponseEntity.badRequest().body(R.error("密码错误"));
        }else{
            //使用mobile字段设置令牌
            Map<String,Object> claims=new HashMap<>();
            claims.put("mobile",loginUser.getMobile());
            String token=jwtUtil.genToken(claims);
//            log.info("获取的token:{}",token);
            System.out.println("userid:"+user.getId());
            //将用户id存入缓存
            redisUtil.setLoginUserId(token,user.getId()+"");

            Map<String, Object> result = new HashMap<>();
            result.put("access_token", token);
            result.put("expires_in", 3600 * 24); // 设置token过期时间
            return ResponseEntity.ok(R.success(result));
        }
    }

    /**
     * 注册接口
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/register")
    public ResponseEntity<R<String>> register(@RequestBody Map map) throws Exception {
//        log.info(map.toString());
        String mobile=((String)map.get("mobile")).trim();
        //判断验证码是否正确，需要使用redis服务
        String code= redisUtil.getCode(mobile);
        if(code==null||!code.equals(map.get("sms_code"))) {
            return ResponseEntity.badRequest().body(R.error("验证码错误或已过期"));
        }else{
            //删除验证码
            redisUtil.deleteCode(mobile);
        }
        //查询用户
        Users user=usersService.getUserByMobile(mobile);
        if(user==null) {
            user=new Users();
            user.setMobile(mobile);
            user.setPassword(RSAUtil.decrypt((String)map.get("password"), privateKey));
            user.setNickname(map.get("nickname").toString());
            user.setGender(3);
            user.setIs_robot(1);
            user.setCreated_at(LocalDateTime.now());
            user.setUpdated_at(LocalDateTime.now());
//            log.info("调用save");
            usersService.save(user);
            return ResponseEntity.ok(R.success("注册成功"));
        }
        return ResponseEntity.badRequest().body(R.error("用户已存在"));
    }

    /**
     * 找回密码
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping("/forget")
    public ResponseEntity<R<String>> forget(@RequestBody Map map) throws Exception {
        String mobile=((String)map.get("mobile")).trim();
        //判断验证码是否正确，需要使用redis服务
        String code= redisUtil.getCode(mobile);
        if(code==null||!code.equals(map.get("sms_code"))) {
            return ResponseEntity.badRequest().body(R.error("验证码错误或已过期"));
        }else{
            //删除验证码
            redisUtil.deleteCode(mobile);
        }
        //查询用户是否存在
        Users user=usersService.getUserByMobile(mobile);
        if(user==null) {
            //用户不存在
            return ResponseEntity.badRequest().body(R.error("用户不存在"));
        }else{//用户存在
            //设置新密码
            user.setPassword(RSAUtil.decrypt((String)map.get("password"), privateKey));
            //设置修改时间
            user.setUpdated_at(LocalDateTime.now());
            usersService.updateById(user);
            return ResponseEntity.ok(R.success("找回成功"));
        }
    }
}
